#-*-coding:utf-8-*-
#!/usr/bin/python

from lib import config, req_sy, db_sy
from lib import email_sy as email
from lib.logger import logger
import codecs
import time
import re

onlive_src = 'twitch'

# 处理来源于Twitch的直播视频，直播地址：http://www.twitch.tv/%s
def _pro_onlivedata_from_twitch(zbid):
	# http://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=raizqt
	if zbid != '':
		return "http://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=%s" % zbid
	else:
		return ''

def get_data_action(is_get_livedata = True):
	game_type = config.TWITCH_GAME
	# twitch视频列表页api:http://streams.twitch.tv/kraken/streams?limit=30&offset=0&broadcaster_language=&on_site=1
	page_size = 30
	page = 0
	# 在线人数作为是否继续爬取的判断条件
	top_views = 100
	res_data = []
	while page < 200 and top_views > 50:
		if not is_get_livedata:
			time.sleep(1)
		top_views = 49
		start_index = page * page_size
		twitch_api = config.TWITCH_API % (page_size, start_index)
		response = req_sy.get_html(twitch_api, is_json=True)
		if response and len(response['streams']) != 0:
			res_list = response['streams']
			for zb in res_list:
				kw = {}
				gameHostName = zb['game']
				if gameHostName not in game_type:
					continue
				views = int(zb['viewers'])
				if top_views < views:
					top_views = views
				logger.info(str(page) + ', views:'+ str(views) + ',top_views:'+ str(top_views) + ',' + gameHostName)
				channel = zb['channel']
				zbid = channel['name']
				kw['zbid'] = zbid
				#if is_get_livedata:
				kw['livedata'] = _pro_onlivedata_from_twitch(zbid)
				kw['zbname'] = channel['display_name']
				kw['source'] = onlive_src
				kw['views'] = views
				kw['title'] = channel['status']
				kw['category'] = game_type[gameHostName]
				kw['inputtime'] = int(time.time())
				if channel['logo']:
					kw['zb_thumb'] = channel['logo']
				else:
					kw['zb_thumb'] = ''
				kw['thumb'] = zb['preview']['large']
				res_data.append(kw)
		else:
			logger.error("%s | %s" % ("get "+onlive_src+" API Failed", twitch_api))
			email.send_email(onlive_src+u'直播API获取失败', "%s | %s" % ("get twitch API Failed", twitch_api))
			top_views = 100
		page = page + 1
	return res_data

if __name__ == "__main__":
	now =  time.time()
	dbconn = db_sy.getConnection()
	update_data = get_data_action(is_get_livedata = False)
	db_sy.db_insert(dbconn, update_data)
	dbconn.close()
	print "time cost : " + str(int((time.time() - now))) + " seconds"
